import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      if (!config.headers.Authorization && store.state.user.token) {
        config.headers.Authorization = `Bearer ${store.state.user.token}`
      }
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    // console.log(response)
    const { isSuccess } = response.data
    if (isSuccess) {
      // Message.success(msg)
      return response.data
    } else {
      // Message.error(message)
      // // 抛出错误
      // return Promise.reject(msg)
    }
  },
  error => {
    // console.dir(error)
    const { message } = error.response.data
    if (error.response.status === 500) {
      Message.error(message)
    }
    return Promise.reject(error)
  }
)

export default service
